var express = require('express');
var router = express.Router();
//引入时间包
const time = require('time-stamp')
//引入Query.js连接数据库
const Query = require('../tools/Query')

router.get('/courses', async (req, res, next) => {

    let { id = ''} = req.query
  
    if(!id){
      next({
        msg:'请传递必要参数'
      })
      return
    }
  
    //查询课程详情根据cid
    //连表查询教师表
    let sql1 = `SELECT cid,title,concat('http://localhost:3000/uploads/course/',detail_imgs) as detail_imgs,concat('http://localhost:3000/uploads/course/',image_src) as image_src,type_name,area_name,category_name,subject_name,grade_name,price,area_name,intro,tid FROM e_course WHERE id='${id}'`
    let  [,result1] = await Query(sql1)
  
    //查询课程具体的视频信息列表
    let sql2 = ` SELECT id,vnum,video_title FROM e_video WHERE id='${id}' ORDER BY vnum ASC`
    let [, result2] = await Query(sql2)
    let sql3 = `SELECT id,tid,realname,intro,concat('http://localhost:3000/uploads/avatar/',head_photo_url) as head_photo_url FROM e_teacher WHERE tid='${result1[0].tid}'`
    let [, result3] = await Query(sql3)
    console.log(result2);
    let data = {
      msg:"OK",
      status:200,
      result:{
        course:result1[0],
        teacher:result3[0],
        videos:result2
      }
    }
    res.send(data)
  
  });
  
  module.exports = router;





router.post('/study', async (req, res, next) => {
    let {cid = '',mid = ''} = req.query

    //id自增的
    //oid通过时间加随机数8位生成的
    let oid = time('YYYYMMMMDDHHmmss') + (Math.random() + '').slice(2, 8)
    // res.send(oid)
    // //cid是自定义的
    // let cid = 'c000002'
    // //mid
    // let mid = "e9cb8d94-db9a-4f80-9064-aa0e74956901"
    //createDate创建现在时间
    let createDate = Date.now()
    //查询
    let sql = `SELECT * FROM e_order WHERE cid='${cid}'`
    let [, result1] = await Query(sql)
    //同样的课程只能添加一次 判断
    if (result1.length > 0) {
        next({
            msg: "该课程已申请过",
            status:200
        })
        return
    } else {
        //向数据库中添加
        let addCourse = `INSERT INTO e_order(oid,cid,mid,createdate,status) VALUES ('${oid}','${cid}','${mid}','${createDate}','1')`

        //执行
        let result = await Query(addCourse)
        let data = {
            msg:'ok',
            result,
            cid,
            mid
        }

        res.send(data)
    }


})
module.exports = router;